/** @format */
import {deepMerge, isPlainObject} from './utils';
import {Methods} from '../types/index';

// 防止用户输入的headers参数大小写问题,content-type,Content-Type
function normalizeHeaderName(headers: any, normalizedName: string): void {
  if (!headers) return;
  Object.keys(headers).forEach(name => {
    if (name !== normalizedName && name.toLowerCase() === normalizedName.toLowerCase()) {
      headers[normalizedName] = headers[name];
      delete headers[name];
    }
  });
}

export function processHeaders(headers: any, data: any): any {
  normalizeHeaderName(headers, 'Content-Type');
  if (isPlainObject(data)) {
    if (headers && !headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=utf-8';
    }
  }
  return headers;
}

// parse Response Headers
export function parseHeaders(headers: string): any {
  const parsed = Object.create(null);
  if (!headers) {
    return parsed;
  }
  headers.split('\r\n').forEach(line => {
    let [key, val] = line.split(':');
    key = key.trim().toLowerCase();
    if (!key) {
      return;
    }
    if (val) {
      val = val.trim();
    }
    parsed[key] = val;
  });
  return parsed;
}

/*
扁平化headers:
headers: {
  common: {Accept:'application/json'},
  post: {Content-Type: 'application/x-www-urlencoded'}
}
转换为:
headers: {
  Accept:'application/json',
  Content-Type: 'application/x-www-urlencoded'
}
 */
export function flattenHeaders(headers: any, method: Methods): any {
  if (!headers) {
    return headers;
  }
  headers = deepMerge(headers.common, headers[method], headers);
  const methodsToDel = ['delete', 'get', 'post', 'head', 'options', 'put', 'patch', 'common'];
  methodsToDel.forEach(method => {
    delete headers[method];
  });
  return headers;
}
